﻿using BW.Mes.WinForms.WareHouse.Dto;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BW.Mes.WinForms.WareHouse.Libraryrecord
{
    public partial class CreateLibraryrecordForm : DevExpress.XtraEditors.XtraForm
    {

        public delegate void LibraryrecordAddedEventHandler(object sender, EventArgs e);
        public event LibraryrecordAddedEventHandler LibraryrecordAdded;

        // 触发事件的方法
        protected virtual void OnLibraryrecordAdded()
        {
            LibraryrecordAdded?.Invoke(this, EventArgs.Empty);
        }


        public CreateLibraryrecordForm()
        {
            InitializeComponent();
            this.Load += CreateLibraryrecordForm_Load;
        }
        
        private void CreateLibraryrecordForm_Load(object sender, EventArgs e)
        {
            LoadLibraryrecord();
            ReceiptsLoadLibraryrecord();
            LoadStoragelocation();
            LoadMaterial();
        }
        
        /// <summary>
        /// 手动加载类型数据到gridLookUpEdit1
        /// </summary>
        private void LoadLibraryrecord()
        {
            // 创建物料数据列表
            List<BankModel> materialList = new List<BankModel>
            {
                new BankModel { Id = "出库", productName = "出库" },
                new BankModel { Id = "入库", productName = "入库" },
                // 可以继续添加更多物料数据
            };
            
            // 设置数据源
            gridLookUpEdit1.Properties.DataSource = materialList;
            gridLookUpEdit1.Properties.DisplayMember = "productName";
            gridLookUpEdit1.Properties.ValueMember = "Id";
            
            // 配置下拉框显示列
            gridLookUpEdit1.Properties.View.Columns.Clear();
            gridLookUpEdit1.Properties.View.Columns.Add(
                new DevExpress.XtraGrid.Columns.GridColumn
                {
                    FieldName = "productName",
                    Caption = "类型名称",
                    Visible = true
                }
            );
            
            // 设置默认提示文本
            gridLookUpEdit1.Properties.NullText = "请选择类型";
        }
        
        /// <summary>
        /// 类型
        /// </summary>
        public class BankModel
        {
            public string Id { get; set; }
            public string productName { get; set; }
        }
        /// <summary>
        /// 单据类型
        /// </summary>
        public class ReceiptsBankModel
        {
            public string Id { get; set; }
            public string Name { get; set; }
        }

        /// <summary>
        /// 单据类型列表
        /// </summary>
        private void ReceiptsLoadLibraryrecord()
        {
            // 创建物料数据列表
            List<ReceiptsBankModel> materialList = new List<ReceiptsBankModel>
            {
                new ReceiptsBankModel { Id = "采购入库", Name = "采购入库" },
                new ReceiptsBankModel { Id = "生产入库", Name = "生产入库" },
                new ReceiptsBankModel { Id = "采购出库", Name = "采购出库" },
                new ReceiptsBankModel { Id = "生产出库", Name = "生产出库" },
                new ReceiptsBankModel { Id = "供应商出库", Name = "供应商出库" },
                new ReceiptsBankModel { Id = "供应商入库", Name = "供应商入库" },
                // 可以继续添加更多物料数据
            };

            // 设置数据源
            gridLookUpEdit2.Properties.DataSource = materialList;
            gridLookUpEdit2.Properties.DisplayMember = "Name";
            gridLookUpEdit2.Properties.ValueMember = "Id";

            // 配置下拉框显示列
            gridLookUpEdit2.Properties.View.Columns.Clear();
            gridLookUpEdit2.Properties.View.Columns.Add(
                new DevExpress.XtraGrid.Columns.GridColumn
                {
                    FieldName = "Name",
                    Caption = "单据类型名称",
                    Visible = true
                }
            );

            // 设置默认提示文本
            gridLookUpEdit2.Properties.NullText = "请选择单据类型";
        }


        /// <summary>
        /// 加载物料信息
        /// </summary>
        private async void LoadMaterial()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    var response = await client.GetAsync("T2/Product/GetProduct?PageIndex=1&PageSize=100");

                    response.EnsureSuccessStatusCode();
                    var responseBody = await response.Content.ReadAsStringAsync();
                    var jsonObject = JsonConvert.DeserializeObject<dynamic>(responseBody);

                    if (jsonObject["pageDatas"] != null)
                    {
                        // 将pageDatas转换为WareHouseItem列表
                        var dataJson = jsonObject["pageDatas"].ToString();
                        var warehouses = JsonConvert.DeserializeObject<List<Material>>(dataJson);

                        // 假设您改用了gridLookUpEdit1控件
                        gridLookUpEdit3.Properties.DataSource = warehouses;
                        gridLookUpEdit3.Properties.DisplayMember = "productName";
                        gridLookUpEdit3.Properties.ValueMember = "Id";

                        // 配置下拉框，只显示供应商名称
                        gridLookUpEdit3.Properties.View.Columns.Clear();
                        gridLookUpEdit3.Properties.View.Columns.Add(
                            new DevExpress.XtraGrid.Columns.GridColumn
                            {
                                FieldName = "productName",
                                Caption = "物料名称",
                                Visible = true
                            }
                        );

                        // 设置默认提示文本
                        gridLookUpEdit3.Properties.NullText = "请选择物料";
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载物料数据失败: {ex.Message}", "错误");
            }
        }


        /// <summary>
        /// 物料
        /// </summary>
        public class Material
        {
            public long Id { get; set; }
            public string productName { get; set; }
        }



        /// <summary>
        /// 加载库位信息
        /// </summary>
        private async void LoadStoragelocation()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    var response = await client.GetAsync("T3/Storagelocation/GetStoragelocation?PageIndex=1&PageSize=100");

                    response.EnsureSuccessStatusCode();
                    var responseBody = await response.Content.ReadAsStringAsync();
                    var jsonObject = JsonConvert.DeserializeObject<dynamic>(responseBody);

                    if (jsonObject["pageDatas"] != null)
                    {
                        // 将pageDatas转换为WareHouseItem列表
                        var dataJson = jsonObject["pageDatas"].ToString();
                        var warehouses = JsonConvert.DeserializeObject<List<Storage>>(dataJson);

                        // 假设您改用了gridLookUpEdit1控件
                        gridLookUpEdit4.Properties.DataSource = warehouses;
                        gridLookUpEdit4.Properties.DisplayMember = "storageLocationName";
                        gridLookUpEdit4.Properties.ValueMember = "Id";

                        // 配置下拉框，只显示供应商名称
                        gridLookUpEdit4.Properties.View.Columns.Clear();
                        gridLookUpEdit4.Properties.View.Columns.Add(
                            new DevExpress.XtraGrid.Columns.GridColumn
                            {
                                FieldName = "storageLocationName",
                                Caption = "库位名称",
                                Visible = true
                            }
                        );

                        // 设置默认提示文本
                        gridLookUpEdit4.Properties.NullText = "请选择库位";
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载库位数据失败: {ex.Message}", "错误");
            }
        }


        /// <summary>
        /// 库位
        /// </summary>
        public class Storage
        {
            public long Id { get; set; }
            public string storageLocationName { get; set; }
        }































        /// <summary>
        /// 取消按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private async void simpleButton2_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(textEdit1.Text))
                {
                    XtraMessageBox.Show("请输入单号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 验证必填字段
                if (gridLookUpEdit1.EditValue == null || string.IsNullOrEmpty(gridLookUpEdit1.EditValue.ToString()))
                {
                    XtraMessageBox.Show("请选择类型", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                
                if (gridLookUpEdit2.EditValue == null || string.IsNullOrEmpty(gridLookUpEdit2.EditValue.ToString()))
                {
                    XtraMessageBox.Show("请选择单据类型", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                
                if (gridLookUpEdit3.EditValue == null)
                {
                    XtraMessageBox.Show("请选择物料", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                
                if (gridLookUpEdit4.EditValue == null)
                {
                    XtraMessageBox.Show("请选择库位", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                
                if (string.IsNullOrEmpty(textEdit2.Text))
                {
                    XtraMessageBox.Show("请输入数量", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                
                // 创建请求数据
                var libraryrecord = new AddLibraryrecordModel()
                {
                   EnterTime=dateEdit1.DateTime,
                   LibraryNumber=int.Parse(textEdit2.Text),
                   Oddnumber=textEdit1.Text,
                   Operation=gridLookUpEdit1.EditValue.ToString(),
                   Receiptstype=gridLookUpEdit2.EditValue.ToString(),
                   Product=long.Parse(gridLookUpEdit3.EditValue.ToString()),
                   StorageLocationId=long.Parse(gridLookUpEdit4.EditValue.ToString())
                };

                // 发送请求到API
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    //创建JSON数据（转换数据类型）
                    var json = JsonConvert.SerializeObject(libraryrecord);
                    //创建请求内容
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    //发送POST请求
                    var response = await client.PostAsync("T3/Libraryrecord/CreateLibraryrecord", content);
                    //读取响应内容
                    var responseContent = await response.Content.ReadAsStringAsync();

                    //判断是否成功
                    if (response.IsSuccessStatusCode)
                    {
                        try
                        {
                            var result = JsonConvert.DeserializeObject<dynamic>(responseContent);

                            // 检查是否包含错误信息
                            if (result != null && result.code != null && result.code.ToString() != "200")
                            {
                                XtraMessageBox.Show($"保存失败: {result.message}", "错误");
                                return;
                            }

                            // 成功
                            XtraMessageBox.Show("保存成功");

                            // 触发事件通知父窗体刷新数据
                            OnLibraryrecordAdded();

                            this.DialogResult = DialogResult.OK;
                            this.Close();
                        }
                        catch
                        {
                            XtraMessageBox.Show("保存成功");
                            OnLibraryrecordAdded();
                            this.DialogResult = DialogResult.OK;
                            this.Close();
                        }
                    }
                    else
                    {
                        try
                        {
                            var result = JsonConvert.DeserializeObject<dynamic>(responseContent);
                            if (result != null && result.message != null)
                            {
                                XtraMessageBox.Show($"保存失败: {result.message}", "错误");
                            }
                            else
                            {
                                XtraMessageBox.Show("保存失败:" + response.ReasonPhrase, "错误");
                            }
                        }
                        catch
                        {
                            XtraMessageBox.Show("保存失败:" + response.ReasonPhrase, "错误");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"操作异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}